<script setup>
import { ref,computed } from 'vue';
import emitter from '../../../utils/bus';

const cartItems=ref([]);

emitter.on('addToCart',(item) => {
            const cartItem = cartItems.value.find((ci) => ci.name === item.name);
            if (cartItem) {
              cartItem.count++;
            } else {
              cartItems.value.push({ ...item, count: 1 });
            }
            //计算总价
            // calcPrice();
          })

           const addToCart = (item) => {
            const cartItem = cartItems.value.find((ci) => ci.name === item.name);
            if (cartItem) {
              cartItem.count++;
            } else {
              cartItems.value.push({ ...item, count: 1 });
            }
            //计算总价
            // calcPrice();
          };
          const handleChange = (item) => {
            if (item.count <= 0) {
              const index = cartItems.value.indexOf(item);
              if (index > -1) {
                cartItems.value.splice(index, 1);
              }
            }
            // calcPrice();
        };

        const totalPrice = computed(() => {
            return cartItems.value.reduce((total, item) => {
              return (total = total + item.price * item.count);
            }, 0);
          });
</script>

<template>
    <el-container>
        
          <!-- 购物车 -->
          <el-aside>
            <el-card>
              <h2>购物车</h2>
              <div v-if="cartItems.length>0">
                <div v-for="(item,i) in cartItems" :key="i">
                  <el-row>
                    <el-col :span="6"><img :src="item.img" style="width: 100%" /></el-col>
                    <el-col :span="18">{{item.name}}</el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">价格：{{item.price}}</el-col>
                    <el-col :span="12">
                      <el-input-number v-model="item.count" @click="handleChange(item)" size="small" :min="0" :max="item.stock" style="float: right"></el-input-number>
                    </el-col>
                  </el-row>
                  <el-divider />
                </div>
              </div>
              <el-empty v-else></el-empty>
              <el-row>
                <el-col :span="16">总价：{{totalPrice}}</el-col>
                <el-col :span="8"><el-button type="primary">结算</el-button></el-col>
              </el-row>
            </el-card>
          </el-aside>
    </el-container>
</template>

<style scoped></style>